package com.springboot.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.model.bo.UserBO;
import com.springboot.model.po.UserPO;
import com.springboot.model.vo.UserVO;
//import com.springboot.service.CreditService;
import com.springboot.service.UserService;

import util.VerifyUtil;

@RefreshScope	//监听动态刷新
@RestController
@RequestMapping("/users")
public class UserController {
	@Autowired
	UserService userService;
	@Value("${eureka.instance.lease-renewal-interval-in-seconds}")
	private int renewal;
	
	@GetMapping("/login")
    public ResponseEntity login(String userId , String password){ //这里是JWT登录成功把token返回给前端
        String token = userService.login(userId , password);
        if(token.equals("用户不存在！")) {
        	return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Wrong password or userId!");
        }else {
			return ResponseEntity.ok(token);
        }
        	
        	
    }
	
	@GetMapping("/name/{userId}")
	public ResponseEntity getUsername(@PathVariable String userId){ //这里是JWT登录成功把token返回给前端
        String username = userService.getUsername(userId);
        if(username == null) {
        	return ResponseEntity.status(HttpStatus.NOT_FOUND).body("not exist!");
        }else
        	return ResponseEntity.ok("username: " + username);
    }

	@GetMapping("/{userId}")
	public ResponseEntity getUserById(@PathVariable String userId) throws Exception{
		//查询用户是否存在
		int result = userService.getUserById(userId);
		if(result == 0) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("UserVO not found!");
		}else{
			return ResponseEntity.ok("exists");
		}
	}
	
	@PostMapping("/registration")	//重复注册已经处理
	public ResponseEntity register(@RequestBody UserPO user)throws Exception {
		//{userId},#{password},#{userName},#{userSex}
		String token;
		try {
			token = userService.saveUser(user);
		}catch(Exception e) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		}
		if(token != null) {
			return ResponseEntity.ok(token);
		}else {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		}
	}
	
	@GetMapping
	public ResponseEntity getUserByIdByPass(UserPO user ,  @RequestParam String token) throws Exception{
		String userId_target = VerifyUtil.verify(token);
		if(userId_target == null || !user.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		//id , psw，都输入了密码，那么返回值可以包含密码
		UserBO user_1 = userService.getUserByIdByPass(user);
		if(user_1 != null) {
			UserVO uvo = new UserVO();
			uvo.setPassword(user_1.getPassword());
			uvo.setDelTag(user_1.getDelTag());
			uvo.setMaxPoints(user_1.getMaxPoints());
			uvo.setMemLevel(user_1.getMemLevel());
			uvo.setPoints(userService.getPoints(user_1.getUserId()));
			uvo.setUserId(user_1.getUserId());
			uvo.setUserImg(user_1.getUserImg());
			uvo.setUserName(user_1.getUserName());
			uvo.setUserSex(user_1.getUserSex());
			return ResponseEntity.ok(uvo);
		}else {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Wrong password or userId!");
		}
	}
	
	@GetMapping("/secret/{userId}")//不需要token
	public ResponseEntity findSerect(@PathVariable String userId) throws Exception{
		UserBO user_1 = userService.findSerect(userId);
		if(user_1 != null) {
			UserVO uvo = new UserVO();
			uvo.setPassword(user_1.getPassword());
			return ResponseEntity.ok(uvo.getPassword());
		}else {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("NOT FOUND!");
		}
	}
	
	@GetMapping("/points/{userId}")
	public ResponseEntity getPoints(@PathVariable String userId) throws Exception{
		//查询积分
		BigDecimal points = userService.getPoints(userId);
		if(points != null) {
			return ResponseEntity.ok(points);
		}else {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("UserVO not found!");
		}
	}
	
	@GetMapping("/maxPoints/{userId}")
	public ResponseEntity getMaxPoints(@PathVariable String userId) throws Exception{
		//查询累计 
		BigDecimal maxPoints = userService.getMaxPoints(userId);
		if(maxPoints != null) {
			return ResponseEntity.ok(maxPoints);
		}else {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("NOT FOUND!");
		}
	}

	@GetMapping("/memLevels/{userId}")
	public ResponseEntity getMemLevel(@PathVariable String userId)throws Exception {
		//查询等级
		Integer memLevel = userService.getMemLevel(userId);
		if(memLevel == null) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("NOT FOUND!");
		}else {
			return ResponseEntity.ok(memLevel);
		}
	}
	
	@PutMapping("/points")
	public ResponseEntity spendPoints(@RequestBody UserVO user , @RequestParam String token)throws Exception {
		//userId , 扣除的points
		//验证userId和token符合吗
		String userId_target = VerifyUtil.verify(token);
		if(userId_target == null || !user.getUserId().equals(userId_target)) {
			return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");//401
		}
		//消费积分兑换优惠券
		int result = userService.spendPoints(user.getUserId() , user.getPoints());
		if(result == 1) {
			return ResponseEntity.ok("ok");
		}else {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An internal error occurred");
		}
	}

}
